/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.sys.platform.security;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.common.config.Constant;
import com.yami.shop.security.comment.exception.UsernameNotFoundException;
import com.yami.shop.security.comment.model.YamiGrantedAuthority;
import com.yami.shop.security.platform.model.YamiSysUser;
import com.yami.shop.sys.comment.dao.SysMenuMapper;
import com.yami.shop.sys.comment.dao.SysUserMapper;
import com.yami.shop.sys.comment.model.SysMenu;
import com.yami.shop.sys.comment.model.SysUser;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户详细信息
 *
 * @author
 */
@Slf4j
@Primary
@Service
@AllArgsConstructor
public class YamiSysUserDetailsServiceImpl implements UserDetailsService {
	private final SysMenuMapper sysMenuMapper;
	private final SysUserMapper sysUserMapper;

	/**
	 * 用户密码登录
	 *
	 * @param username 用户名
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public YamiSysUser loadUserByUsername(String username) {
		return getUserDetails(username);
	}


	/**
	 * 构建userdetails
	 *
	 * @param username 用户名称
	 * @return
	 */
	private YamiSysUser getUserDetails(String username) {
		SysUser sysUser = sysUserMapper.selectByUsername(username);

		if (sysUser == null) {
			// 未找到此用户信息
			throw new UsernameNotFoundException("yami.user.no.exist");
		}

		Collection<GrantedAuthority> authorities
				= getUserPermissions(sysUser.getUserId());

		// 构造security用户
		YamiSysUser yamiSysUser = new YamiSysUser();
		yamiSysUser.setUsername(sysUser.getUsername());
		yamiSysUser.setPassword(sysUser.getPassword());
		yamiSysUser.setEnabled(sysUser.getStatus() == 1);
		yamiSysUser.setUserId(sysUser.getUserId());
		yamiSysUser.setAuthorities(authorities);
		return yamiSysUser;
	}

	private List<GrantedAuthority> getUserPermissions(Long userId) {
		List<String> permsList;

		//系统管理员，拥有最高权限
		if(userId == Constant.SUPER_ADMIN_ID){
			List<SysMenu> menuList = sysMenuMapper.selectList(Wrappers.emptyWrapper());


			permsList = menuList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
		}else{
			permsList = sysUserMapper.queryAllPerms(userId);
		}


		Set<String> permsSet = permsList.stream().flatMap((perms)->{
					if (StrUtil.isBlank(perms)) {
						return null;
					}
					return Arrays.stream(perms.trim().split(StrUtil.COMMA));
				}
		).collect(Collectors.toSet());

		// 将权限组合成spring 需要的格式
		List<GrantedAuthority> authorities = new ArrayList<>(permsSet.size());

		for (String perms : permsSet) {
			YamiGrantedAuthority yamiGrantedAuthority = new YamiGrantedAuthority();
			yamiGrantedAuthority.setPerms(perms);
			authorities.add(yamiGrantedAuthority);
		}

		return authorities;
	}

}
